import fileinput
import openpyxl
import time

# 定义日志文件名和工作表名
log_file = 'a.log'
sheet_name = 'Log Summary'

# 创建 Excel 工作簿并选择对应工作表
workbook = openpyxl.Workbook()
worksheet = workbook.active
worksheet.title = sheet_name

# 设置日志级别列表.
levels = ['E', 'D', 'W', 'I', 'V']

# 初始化计数器
counters = {level: 0 for level in levels}

# 持续获取日志文件内容并分析日志级别
for line in fileinput.input(log_file):
    # 对每一行分析日志级别

    for level in levels:
        # 如果该行包含当前级别的日志，则计数器+1
        if level == line[0]:
            counters[level] += 1

    # 将计数器结果写入 Excel 工作表
    worksheet.cell(row=1, column=1, value='Log Level')
    worksheet.cell(row=1, column=2, value='Count')
    row_num = 2
    for level in levels:
        count = counters[level]
        worksheet.cell(row=row_num, column=1, value=level)
        worksheet.cell(row=row_num, column=2, value=count)
        row_num += 1

    # 保存 Excel 工作簿
    workbook.save('Log Summary.xlsx')

    # 休眠2秒钟，然后继续读取和分析日志文件
    time.sleep(1)